package com.jwj.testback.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;

@Component
@Slf4j
@Aspect
//@Order(-1)
@Order(-1)

public class DataSourceAspect {

//这里可以自己修改想要以什么方式匹配使用数据源
@Pointcut("@within(com.jwj.testback.config.DataSource) || @annotation(com.jwj.testback.config.DataSource)")
    public void pointCut() {

    }

    //在之前
    @Before("pointCut()")
    public void doBefore(JoinPoint joinPoint) throws ClassNotFoundException, NoSuchMethodException{
        // 参数值
        Object[] args = joinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            System.out.println("参数："+args[i]);
        }

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取被注解注释的方法
        Method method = joinPoint.getTarget().getClass().getMethod(signature.getName(), signature.getMethod().getParameterTypes());

        ParameterNameDiscoverer pnd = new DefaultParameterNameDiscoverer();
        String[] parameterNames = pnd.getParameterNames(method);
        // 通过map封装参数和参数值
        HashMap<String, Object> paramMap = new HashMap();
        for (int i = 0; i < parameterNames.length; i++) {
            paramMap.put(parameterNames[i], args[i]);
//            System.out.println("参数名："+parameterNames[i]+"\n参数值"+args[i]);
        }
        String databaseName = (String) paramMap.get("databaseName");

        if (!MultipleDataSource.containsDataSource(databaseName)){
            //如果数据库中没有，则使用默认数据源
            log.info("数据源不存在，使用默认数据源");
        }else {
            log.info("数据源存在，使用数据源："+databaseName);
            MultipleDataSource.setDataSource(databaseName);
        }

//        return paramMap;
    }



    //在之后
    @After("pointCut()")
    public void doAfter() {
        MultipleDataSource.clear();
    }
}
